package com.kaifamiao.wendao.controller;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Explain;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.service.ExplainService;
import com.kaifamiao.wendao.utils.Constants;
import org.tinylog.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/explain/*")
public class ExplainServlet extends HttpServlet {

    private ExplainService explainService;

    @Override
    public void init() throws ServletException {
        explainService = new ExplainService();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String method = request.getMethod();
        String uri = request.getRequestURI();
        // POST "/explain/publish"
        if( "POST".equals(method) && uri.endsWith( "/publish" )){
            this.publishAction(request,response);
        }

    }

    // POST "/explain/publish"
    protected void publishAction(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Customer c = (Customer)session.getAttribute(Constants.CUSTOMER_LOGINED);
        String tid = request.getParameter("topicId");
        if(this.validatePublish(request)) {
            Long topicId = Long.valueOf(tid);
            Topic t = new Topic();
            t.setId(topicId);
            String content = request.getParameter("content");
            String addr = request.getRemoteAddr();

            Explain e = new Explain();
            e.setContent(content);
            e.setPublishAddress(addr);
            e.setAuthor(c);
            e.setTopic(t);

            try {
                if (explainService.save(e)) {
                    response.sendRedirect(request.getContextPath()+"/topic/detail?id=" + tid);
                    return;
                }
            } catch (Exception ex) {
                Logger.error(ex);
            }
            session.setAttribute("message", "保存失败");
            session.setAttribute("content", content);
        }
        response.sendRedirect(request.getContextPath() + "/topic/"+tid+"/explain");
    }


    private boolean validatePublish(HttpServletRequest request) {

        return true;
    }

}
